package br.unipar.lhmicheletti.manager;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.transaction.annotation.Transactional;

import br.unipar.lhmicheletti.entity.Turma;

import static com.google.code.liquidform.LiquidForm.*;

public class TurmaManager {
	
	@PersistenceContext
	private EntityManager entityManager;
	
	@Transactional( readOnly=false )
	public Turma salvarTurma( Turma turma ){
		entityManager.persist( turma );
		
		return turma;
	}
	
	@Transactional( readOnly=false )
	public void excluirTurma( Turma turma ){
		entityManager.remove( turma );
	}
	
	@Transactional( readOnly=true )
	public List<Turma> buscarTodos(){
		
		Turma t = alias( Turma.class, "t" );
		
		String query = select(t).from(Turma.class).as(t).toString();
		
		List<Turma> listaTurmas = entityManager.createQuery( query ).getResultList();
		
		return listaTurmas;
	}
	
	@Transactional( readOnly=true )
	public Turma buscarTurma( String id ){
		Turma t = alias( Turma.class, "t" );
		
		String consulta = select( t ).from( Turma.class ).as( t )
		                  .where( eq( t.getId(), Long.parseLong( id ) ) ).toString();
		
		Turma turma = (Turma)entityManager.createQuery( consulta ).getSingleResult();
		
		return turma;
	}
}
